package com.zzxx.www.web;

import com.zzxx.www.domain.Admin;
import com.zzxx.www.domain.User;
import com.zzxx.www.service.impl.LoginServiceImpl;
import com.zzxx.www.utils.LoginException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
	private LoginServiceImpl loginService = new LoginServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		if (request.getSession().getAttribute("checkcode_session").equals(request.getParameter("verifycode"))){
			String loginname = request.getParameter("username");
			String password = request.getParameter("password");
			try {
				Admin admin = loginService.login(loginname, password);
				response.sendRedirect("index.html");
			} catch (LoginException e) {
				request.setAttribute("errorMessage",e.getMessage());
				request.getRequestDispatcher("login.jsp").forward(request,response);
			}
		}else{
			request.setAttribute("errorMessage","验证码错误");
			request.getRequestDispatcher("login.jsp").forward(request,response);
		}

	}
}
